package com.example.ctrip.plugs;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.ctrip.utils.ApplicationContextUtil;
import com.example.ctrip.utils.ImageUtil;
import com.example.ctrip.utils.OpenCvUtil;
import com.example.ctrip.utils.SeleniumUtil;
import com.example.ctrip.commons.Commons;
import com.example.ctrip.entity.OrderTicketActiviti;
import com.example.ctrip.entity.OrderTicketInfo;
import com.example.ctrip.entity.StepReturn;
import com.example.ctrip.service.Impl.OrderActivitiServiceImpl;
import com.example.ctrip.service.Impl.OrderInfoServiceImpl;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

import static com.example.ctrip.commons.CommWebTools.*;

public class payFlight {
    private final static Logger logger = LoggerFactory.getLogger(payFlight.class);
//
//    @Autowired
//    OrderInfoService orderInfoService;
//
//    @Autowired
//    OrderActivitiService orderActivitiService;

    WebDriver webDriver;

    JSONObject paramJson;
    String username;
    String password;
    String airCode;
    String depDate;
    String cabinCode;
    String hd_zcw;
    String depCity;
    String arrCity;
    String passengers;
    String cpry;
    String ddbh;
    String hbxx;
    String smallpnr;
    String cookie;
    String adultPrice;
    Integer adultFund;
    Integer adultFueloil;
    JSONArray passenger;
    int creatOrderState;
    int cgje1;
    WebDriver newWindow = null;
    String FirstHandle;

    public payFlight(Map<String, String> map, WebDriver _webDriver) {
        webDriver = _webDriver;
        username = map.get("username");
        password = map.get("password");
        paramJson = JSONObject.parseObject(map.get("DETAILS"));
        airCode = paramJson.getString("airCode");
        depDate = paramJson.getString("depDate");
        cabinCode = paramJson.getString("cabinCode") + "舱";
        hd_zcw = paramJson.getString("hd_zcw") + "舱";
        depCity = paramJson.getString("depCity");
        arrCity = paramJson.getString("arrCity");
        passengers = paramJson.getString("passengers");
        passenger = JSONArray.parseArray(passengers);
        cpry = paramJson.getString("cpry");
        ddbh = paramJson.getString("ddbh");
        hbxx = paramJson.getString("hbxx");
        smallpnr = paramJson.getString("smallpnr");
        cookie = paramJson.getString("cookie");
        adultPrice = paramJson.getString("adultPrice");
        adultFund = Integer.parseInt(String.valueOf(paramJson.getString("adultFund")));
        adultFueloil = Integer.parseInt(String.valueOf(paramJson.getString("adultFueloil")));
    }

    public StepReturn Step0() {
        //判断是否合规
        OrderTicketInfo orderTicketInfo = new OrderTicketInfo();
        orderTicketInfo.setAIRLINE("G5");
        orderTicketInfo.setCHANNEL("G5B2C");
        orderTicketInfo.setCPRY(cpry);
        orderTicketInfo.setCREATETIME(new Date());
        orderTicketInfo.setDDBH(ddbh);
        orderTicketInfo.setDETAILS(hbxx);
        orderTicketInfo.setINTIME(new Date());
        orderTicketInfo.setSMALLPNR(smallpnr);
        orderTicketInfo.setPASSENGERS(passengers);
        orderTicketInfo.setORDERPRICE(adultPrice);
        orderTicketInfo.setTOTALFUELTAX(String.valueOf((adultFueloil + adultFund)));
        OrderInfoServiceImpl orderInfoServiceImpl = (OrderInfoServiceImpl) ApplicationContextUtil.getBean("orderInfoServiceImpl");
        orderInfoServiceImpl.insertOrderInfo(orderTicketInfo);
        //判断乘机人人数，如果大于1需要点击新增乘机人按钮
        if (passenger.size() > 3) {
            orderRk(ddbh, "{'code':'1','msg':'请求失败，乘机人大于3人'}", "10");
            return new StepReturn(3, "G5官网最多允许三人购票");
        }

        //登录，输入用户名密码，且点击登录按钮
        try {
            if (webDriver.getCurrentUrl().equals("https://www.chinaexpressair.com/yss/login/")) {
                if (!isJudgingElement(webDriver, By.id("pwdLoginUsername"))) {
                    return new StepReturn(0);
                }
                webDriver.findElement(By.id("pwdLoginUsername")).sendKeys(username);
                webDriver.findElement(By.id("pwdLoginPassword")).sendKeys(password);
                Thread.sleep(2000);
                webDriver.findElement(By.id("pwdLoginBtn")).click();
            }
        } catch (Exception e) {
            return new StepReturn(0);
        }
        return new StepReturn(1);
    }

    public StepReturn Step1() {
        //破解云盾
        int tryTimes = 0;
        try {
            int loginTimes = 0;
            while (true) {
                Thread.sleep(3500);
                String url;
                String url1;
                System.out.println(webDriver.findElement(By.className("yidun_bg-img")).getAttribute("src"));
                url = webDriver.findElement(By.className("yidun_bg-img")).getAttribute("src");
                url1 = webDriver.findElement(By.className("yidun_jigsaw")).getAttribute("src");
                while (url == null || url1 == null) {
                    Thread.sleep(500);
                    url = webDriver.findElement(By.className("yidun_bg-img")).getAttribute("src");
                    url1 = webDriver.findElement(By.className("yidun_jigsaw")).getAttribute("src");
                    tryTimes++;
                    if (tryTimes > 50) {
                        //50次都找不到，则要重新刷新页面
                        return new StepReturn(0);
                    }
                }
                //下载并copy图片
                String[] split = url.split("/");
                String fileName = split[split.length - 1];
                File file = new File(Commons.getIMGCODE() + fileName);
                InputStream inputStream = ImageUtil.getInputStreamByGet(url);
                ImageUtil.saveData(inputStream, file);
                ImageUtil.convert(Commons.getIMGCODE() + fileName, "png", Commons.getIMGCODE() + "one.png");

                String[] split1 = url1.split("/");
                String fileName1 = split1[split1.length - 1];
                File file1 = new File(Commons.getIMGCODE() + fileName1);
                InputStream inputStream1 = ImageUtil.getInputStreamByGet(url1);
                ImageUtil.saveData(inputStream1, file1);
                ImageUtil.convert(Commons.getIMGCODE() + fileName1, "png", Commons.getIMGCODE() + "two.png");

                double distance = OpenCvUtil.getDistance("file:///" + Commons.getIMGCODE() + "one.png", "file:///" + Commons.getIMGCODE() + "two.png");
                SeleniumUtil.move(webDriver, webDriver.findElement(By.className("yidun_jigsaw")), (int) distance + 18);

                new File(Commons.getIMGCODE() + "one.png").delete();
                new File(Commons.getIMGCODE() + "two.png").delete();
                file.delete();
                file1.delete();
                Thread.sleep(2000);

                if (!isJudgingElement(webDriver, By.className("yidun_bg-img"))) {
                    //如果yidun背景没有了，证明又没通过验证，又没验证码出现，需要再次点击一下登录按钮
                    webDriver.findElement(By.id("pwdLoginBtn")).click();
                    if (loginTimes++ > 30) {
                        //30次都没拼正确，则要重新刷新页面
                        return new StepReturn(0);
                    }
                }
            }
        } catch (Exception e) {
            //e.printStackTrace();
            if (!isJudgingElement(webDriver, By.className("yidun_bg-img"))) {
                return new StepReturn(1);
            }
            return Step1();
        }
    }

    public StepReturn Step2() {
        //查询航班
        JSONObject jsonObject = null;
        webDriver.get("https://www.chinaexpressair.com/yss/flight-search/bookingOneTrip");
        //查询航班
        try {
            /**
             * 登陆完毕，接着处理后续任务
             */
            if (isJudgingElements(webDriver, By.className("datepicker"))) {
                ((JavascriptExecutor) webDriver).executeScript("document.getElementById(\"cityBegin\").setAttribute(\"threecode\",\"" + depCity + "\")");
                ((JavascriptExecutor) webDriver).executeScript("document.getElementById(\"cityEnd\").setAttribute(\"threecode\",\"" + arrCity + "\")");
                ((JavascriptExecutor) webDriver).executeScript("document.getElementsByClassName(\"datepicker\")[0].removeAttribute(\"readonly\")");
                ((JavascriptExecutor) webDriver).executeScript("Object.defineProperties(navigator,{ webdriver:{ get: () => false } })");
                Thread.sleep(1000);
                webDriver.findElement(By.className("datepicker")).clear();
                Thread.sleep(1000);
                webDriver.findElement(By.className("datepicker")).sendKeys(depDate);
                webDriver.findElement(By.className("tri-cdtion-btn")).click();
            } else {
                return new StepReturn(0);
            }

            Thread.sleep(1000);
            if (isJudgingElements(webDriver, By.id("nc_1_n1z"))) {
                SeleniumUtil.move(webDriver, webDriver.findElement(By.id("nc_1_n1z")), 300);
            } else {
                return new StepReturn(0);
            }

            List<WebElement> lis = new LinkedList<WebElement>();
            if (isJudgingElements(webDriver, By.className("num"))) {
                lis = webDriver.findElements(By.className("num"));
            } else {
                return new StepReturn(0);
            }

            if (lis.size() == 0) {
                return new StepReturn(3, "无对应航班");
            }
            //遍历航班号定位对应的航班
            Thread.sleep(2000);
            int i;
            boolean isFind = false;
            /**
             * 寻找航班
             */
            for (i = 0; i < lis.size(); i++) {
                if (lis.get(i).getText().equals(airCode)) {
                    isFind = true;
                    break;
                }
            }

            if (!isFind) {
                return new StepReturn(3, "无对应航班");
            }

            //点击对应的订票按钮
            if (isJudgingElements(webDriver, By.className("acas-btn"))) {
                webDriver.findElements(By.className("acas-btn")).get(i).click();
            } else {
                return new StepReturn(3, "无对应航班");
            }

            Thread.sleep(2000);
            //获取每个舱位
            List<WebElement> cabinCodes = new LinkedList<>();
            if (isJudgingElements(webDriver, By.className("cabin"))) {
                cabinCodes = webDriver.findElements(By.className("cabin"));
            } else {
                return new StepReturn(3, "无对应舱位");
            }

            /**
             * 寻找舱位
             */
            isFind = false;
            //遍历舱位定位对应的舱位的票
            for (i = 0; i < cabinCodes.size(); i++) {
                System.out.println(cabinCodes.get(i).getText());
                if (cabinCodes.get(i).getText().equals(cabinCode) || cabinCodes.get(i).getText().equals(hd_zcw)) {
                    isFind = true;
                    break;
                }
            }
            if (!isFind) {
                return new StepReturn(3, "无对应舱位");
            }

            //如果找到对应机票,点击订票
            List<WebElement> chksel = new LinkedList<>();
            if (isJudgingElements(webDriver, By.className("chk_sel"))) {
                chksel = webDriver.findElements(By.className("chk_sel"));
            } else {
                return new StepReturn(3, "无对应舱位");
            }

            /**
             * 寻找对应机票按钮
             */
            isFind = false;
            for (i = 0; i < chksel.size(); i++) {
                if (chksel.get(i).getText() != null && !chksel.get(i).getText().equals("")) {
                    isFind = true;
                    break;
                }
            }
            if (!isFind) {
                return new StepReturn(3, "无对应舱位按钮");
            }
            chksel.get(i).click();

            Thread.sleep(2000);
            //获取票价信息(价格是通过js动态加载的，需要用js或者jquery进行抓取)
            String adultPricee = (String) ((JavascriptExecutor) webDriver).executeScript("return $(\".adult_price\").children(\"em\").text()");
            int adultPrice = Integer.parseInt(adultPricee.substring(1));

            //机建费
            String adultFundd = (String) ((JavascriptExecutor) webDriver).executeScript("return $(\".adult_fund\").children(\"em\").text()");
            int adultFund = Integer.parseInt(adultFundd.substring(1));

            //燃油费
            String adultFueloill = (String) ((JavascriptExecutor) webDriver).executeScript("return $(\".adult_fueloil\").children(\"em\").text()");
            int adultFueloil = Integer.parseInt(adultFueloill.substring(1));

            //查询到需要返回的json
            jsonObject = new JSONObject();
            jsonObject.put("adultPrice", adultPrice);
            jsonObject.put("adultFund", adultFund);
            jsonObject.put("adultFueloil", adultFueloil);
        } catch (Exception e) {
            //刷新页面重试
            return new StepReturn(0);
        }
        return new StepReturn(1);
    }

    public StepReturn Step3() {
        try {
            String ccccgje = (String) ((JavascriptExecutor) webDriver).executeScript("return $(\".adult_price\").children(\"em\").text()");
            cgje1 = (Double.valueOf(ccccgje.substring(1)).intValue() + adultFund) * passenger.size();

            int i;
            for (i = 0; i < passenger.size() - 1; i++) {
                webDriver.findElement(By.id("add_traveler")).click();
                //判断座位是否足够
                if (isJudgingElement(webDriver, By.className("col-md-text"))) {
                    return new StepReturn(3, "航班舱位剩余座位不足");
                }
            }

            List<WebElement> cnNames = webDriver.findElements(By.className("cnName"));
            List<WebElement> idNos = webDriver.findElements(By.name("idNo"));
            //List<WebElement> birthDays = webDriver.findElements(By.name("birthDay"));
            List<WebElement> phones = webDriver.findElements(By.name("phone"));
            for (int x = 0; x < cnNames.size(); x++) {
                cnNames.get(x).sendKeys(passenger.getJSONObject(x).getString("name"));
                idNos.get(x).sendKeys(passenger.getJSONObject(x).getString("idCard"));
                //TODO 此处有问题，需判断，是否是身份证，如果是其他证件，应该会存在问题，一个是下拉选择其他证件，一个是生日自动输入这2个问题
                //((JavascriptExecutor) webDriver).executeScript("document.getElementsByClassName(\"datetime_birthday\")[x].removeAttribute(\"readonly\")");
                //birthDays.get(x).sendKeys(passenger.getJSONObject(x).getString("birthday"));
                phones.get(x).sendKeys(passenger.getJSONObject(x).getString("phone"));
            }

            System.out.println("1");
            webDriver.findElement(By.name("linkManName")).clear();
            webDriver.findElement(By.name("linkPhone")).clear();
            webDriver.findElement(By.name("linkManName")).sendKeys(passenger.getJSONObject(0).getString("lxr"));
            webDriver.findElement(By.name("linkPhone")).sendKeys(passenger.getJSONObject(0).getString("phone"));

            System.out.println("2");
            webDriver.findElement(By.id("declaration")).click();
            Thread.sleep(2000);
            webDriver.findElement(By.id("next_end_step")).click();
            Thread.sleep(3000);
        } catch (Exception e) {
            return new StepReturn(0);
        }
        return new StepReturn(1);
    }

    public StepReturn Step4() {
        try {
            ((JavascriptExecutor) webDriver).executeScript("window.location.href = url+\"/user/sale-pnr/vasView/?token=\"+token;");
            System.out.println("3");
            Thread.sleep(2000);
            if (isJudgingElements(webDriver, By.id("next_step"))) {
                webDriver.findElement(By.id("next_step")).click();
            } else {
                orderRk(ddbh, "{'code':'1','msg':'请求超时'}", "10");
                return new StepReturn(0);
            }
        } catch (Exception e) {
            return new StepReturn(0);
        }
        return new StepReturn(1);
    }

    public StepReturn Step5() {
        try {
            System.out.println("4");
            Thread.sleep(3000);
            //isJudgingElements(webDriver, By.id("next_step_other"));
            if (isJudgingElements(webDriver, By.id("next_step_other"))) {
                webDriver.findElement(By.id("next_step_other")).click();
            } else {
                orderRk(ddbh, "{'code':'1','msg':'请求超时'}", "10");
                return new StepReturn(0);
            }
            Thread.sleep(1000);
        } catch (Exception e) {
            return new StepReturn(0);
        }
        return new StepReturn(1);
    }

    public StepReturn Step6() {
        //破解云盾
        int tryTimes = 0;
        try {
            int loginTimes = 0;
            while (true) {
                Thread.sleep(3500);
                String url;
                String url1;
                System.out.println(webDriver.findElement(By.className("yidun_bg-img")).getAttribute("src"));
                url = webDriver.findElement(By.className("yidun_bg-img")).getAttribute("src");
                url1 = webDriver.findElement(By.className("yidun_jigsaw")).getAttribute("src");
                while (url == null || url1 == null) {
                    Thread.sleep(500);
                    url = webDriver.findElement(By.className("yidun_bg-img")).getAttribute("src");
                    url1 = webDriver.findElement(By.className("yidun_jigsaw")).getAttribute("src");
                    tryTimes++;
                    if (tryTimes > 50) {
                        //50次都找不到，则要重新刷新页面
                        return new StepReturn(0);
                    }
                }
                //下载并copy图片
                String[] split = url.split("/");
                String fileName = split[split.length - 1];
                File file = new File(Commons.getIMGCODE() + fileName);
                InputStream inputStream = ImageUtil.getInputStreamByGet(url);
                ImageUtil.saveData(inputStream, file);
                ImageUtil.convert(Commons.getIMGCODE() + fileName, "png", Commons.getIMGCODE() + "one.png");

                String[] split1 = url1.split("/");
                String fileName1 = split1[split1.length - 1];
                File file1 = new File(Commons.getIMGCODE() + fileName1);
                InputStream inputStream1 = ImageUtil.getInputStreamByGet(url1);
                ImageUtil.saveData(inputStream1, file1);
                ImageUtil.convert(Commons.getIMGCODE() + fileName1, "png", Commons.getIMGCODE() + "two.png");

                double distance = OpenCvUtil.getDistance("file:///" + Commons.getIMGCODE() + "one.png", "file:///" + Commons.getIMGCODE() + "two.png");
                SeleniumUtil.move(webDriver, webDriver.findElement(By.className("yidun_jigsaw")), (int) distance + 18);

                new File(Commons.getIMGCODE() + "one.png").delete();
                new File(Commons.getIMGCODE() + "two.png").delete();
                file.delete();
                file1.delete();
                Thread.sleep(2000);

                if (!isJudgingElement(webDriver, By.className("yidun_bg-img"))) {
                    //如果yidun背景没有了，证明又没通过验证，又没验证码出现，需要再次点击一下登录按钮
                    webDriver.findElement(By.id("next_step_other")).click();
                    if (loginTimes++ > 30) {
                        //30次都没拼正确，则要重新刷新页面
                        return new StepReturn(0);
                    }
                }
            }
        } catch (Exception e) {
            //e.printStackTrace();
            if (!isJudgingElement(webDriver, By.className("yidun_bg-img"))) {
                return new StepReturn(1);
            }
            return Step6();
        }
    }

    public StepReturn Step7() {
        try {
            System.out.println("5");
            Thread.sleep(2000);

            System.out.println("6");
//            if (creatOrderState == 1) {
//                System.out.println("7");
//                orderRk(ddbh, "{'code':'1','msg':'创建订单成功'}", "11");
//            } else {
//                System.out.println("8");
//                orderRk(ddbh, "{'code':'0','msg':'创建订单失败'}", "10");
//                //return new ReturnAjax("202", "fail", "创建订单失败", "创建订单失败");
//            }
            System.out.println("7");
            orderRk(ddbh, "{'code':'1','msg':'创建订单成功'}", "11");
            System.out.println("9");

            System.out.println("支付开始，寻找p_YEEPAY标签");
            if (isJudgingElements(webDriver, By.id("p_YEEPAY"))) {
                System.out.println("已找到p_YEEPAY标签，准备点击");
                webDriver.findElement(By.id("p_YEEPAY")).click();
                System.out.println("已点击p_YEEPAY标签");
            } else {
                System.out.println("未找到p_YEEPAY标签，刷新页面");
                orderRk(ddbh, "{'code':'1','msg':'请求超时'}", "10");
                return new StepReturn(0);
            }

            Thread.sleep(8000);
            //得到最先的窗口权柄
            FirstHandle = webDriver.getWindowHandle();
            newWindow = null;
            //得到浏览器所有窗口的权柄为Set集合，遍历
            for (String winHandle : webDriver.getWindowHandles()) {
                //如果为 最先的窗口 权柄跳出
                if (winHandle.equals(FirstHandle)) {
                    continue;
                }
                //如果不为 最先的窗口 权柄，将 新窗口的操作权柄  给 driver
                newWindow = webDriver.switchTo().window(winHandle);
                //打印是否为新窗口
                System.out.println(webDriver.getCurrentUrl());
                break;
            }
            Thread.sleep(2000);
        } catch (Exception e) {
            return new StepReturn(0);
        }
        return new StepReturn(1);
    }

    public StepReturn Step8() {
        try {
            //填写易宝无卡支付信息
            try {
                List<WebElement> yeePayList = new LinkedList<>();
                if (isJudgingElements(webDriver, By.className("tool-handler"))) {
                    yeePayList = webDriver.findElements(By.className("tool-handler"));
                    yeePayList.get(yeePayList.size() - 1).click();
                } else {
                    return new StepReturn(0);
                }
                if (isJudgingElements(webDriver, By.id("cardno"))) {
                    Thread.sleep(1000);
                    webDriver.findElement(By.id("cardno")).sendKeys("6222350108844984");
                    Thread.sleep(1000);
                    webDriver.findElement(By.name("valid")).sendKeys("0822");
                    Thread.sleep(1000);
                    webDriver.findElement(By.name("cvv2")).sendKeys("230");
                    Thread.sleep(1000);
                    webDriver.findElement(By.name("phone")).sendKeys("18716664768");
                    Thread.sleep(1000);
                    webDriver.findElement(By.id("firstPayBtn")).click();
                } else {
                    return new StepReturn(0);
                }
            } catch (Exception e) {
                return new StepReturn(0);
            }

            Thread.sleep(11000);
            if (!isJudgingElements(webDriver, By.className("zfk-f"))) {
                return new StepReturn(0);
            }
        } catch (InterruptedException e) {
            return new StepReturn(0);
        }
        return new StepReturn(1);
    }

    public StepReturn Step9() {
        try {
            /**
             * 支付成功，入库
             */
            //判断是否出票成功
            while (!webDriver.findElement(By.className("dd-wc")).getText().equals("出票完成")) {
                return new StepReturn(0);
            }
            String orderNo = webDriver.findElement(By.className("zfk-f")).getText().substring(4);
            List<WebElement> payNoList = webDriver.findElements(By.className("dqx-f6"));
            List<WebElement> idCardList = webDriver.findElements(By.className("dqx-f3"));
            JSONObject ticketNo = new JSONObject();
            for (int i = 0; i < passenger.size(); i++) {
                String payNo = payNoList.get(3 + i * 4).getText().substring(3);
                ticketNo.put(idCardList.get(i).getText().substring(5), payNo);
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("orderNo", orderNo);
            jsonObject.put("cgje", cgje1);
            String payData = jsonObject.toJSONString();
            OrderInfoServiceImpl orderInfoServiceImpl = (OrderInfoServiceImpl) ApplicationContextUtil.getBean("orderInfoServiceImpl");
            int payUpState = orderInfoServiceImpl.updatePaydata(ddbh, payData, orderNo);
//            int payUpState = orderInfoService.updatePaydata(ddbh, payData, orderNo);
            if (payUpState == 1) {
                orderRk(ddbh, "{'code':'0','msg':'支付成功'}", "21");
            } else {
                orderRk(ddbh, "{'code':'1','msg':'支付失败'}", "20");
                //return new ReturnAjax("202", "fail", "支付失败", "支付失败");
            }
            System.out.println(orderNo);
            System.out.println(cgje1);
            String payNo = "";
            asmsHuiDan(ddbh, cookie, cgje1, ticketNo, payNo, orderNo, username);

            //关闭新打开的支付窗口，并切换控制权到第一窗口
            newWindow.close();
            webDriver.switchTo().window(FirstHandle);
        } catch (IOException e) {
            e.printStackTrace();
            //asmsHuiDan的错误，先不管
        } catch (Exception e) {
            return new StepReturn(0);
        }
        return new StepReturn(4,"回单成功");
    }

    public static void orderRk(String ddbh, String msg, String status) {
        OrderInfoServiceImpl orderInfoServiceImpl = (OrderInfoServiceImpl) ApplicationContextUtil.getBean("orderInfoServiceImpl");
        OrderTicketInfo orderTicketInfo1 = orderInfoServiceImpl.selectIdByDDBH(ddbh);
//        OrderTicketInfo orderTicketInfo1 = orderInfoService.selectIdByDDBH(ddbh);
        OrderTicketActiviti orderTicketActiviti = new OrderTicketActiviti();
        orderTicketActiviti.setORDER_ID(orderTicketInfo1.getID());
        orderTicketActiviti.setINTIME(new Date());
        orderTicketActiviti.setLOG(msg);
        orderTicketActiviti.setINFO(msg);
        orderTicketActiviti.setSTATUS(status);
        OrderActivitiServiceImpl orderActivitiService = (OrderActivitiServiceImpl) ApplicationContextUtil.getBean("orderActivitiServiceImpl");
        orderActivitiService.insertActiciti(orderTicketActiviti);
//        orderActivitiService.insertActiciti(orderTicketActiviti);
    }

    public JSONObject asmsHuiDan(String ddbh, String asmsCookie, Integer cgje, JSONObject ticketNo, String payNo, String orderID, String username) throws IOException {
        JSONObject res = new JSONObject();

        // 回填订单号
        // String orderNo = ticketNo.getString("orderNo");

        // 基础表单信息
        String urlSetWc = "http://47.107.92.22:8150/asms/ticket/order/zcd/asmslticketorderzcd/setWc?ddbh=" + ddbh + "&pt=asms";
        System.out.println(urlSetWc);
        String resSetWc = commonAsmsGet(urlSetWc, asmsCookie);
        Document docSetWc = Jsoup.parse(resSetWc);
        Elements formElementSetWc = docSetWc.select("form").eq(0).select("input");
        JSONObject setWc = new JSONObject();
        for (int i = 0; i < formElementSetWc.size(); i++) {
            String name = formElementSetWc.eq(i).attr("name");
            String val = formElementSetWc.eq(i).val();
            setWc.put(name, val);
        }
        String p = setWc.getString("p");
        String submitForm = setWc.getString("submitForm");
        String fysje = setWc.getString("fysje");
        String ddbhStr = setWc.getString("ddbh");
        String ddzt = setWc.getString("ddzt");
        String pnr_hkgstldatetime = setWc.getString("pnr_hkgstldatetime");
        String zkfx = setWc.getString("zkfx");
        String ps_pszt = setWc.getString("ps_pszt");
        String pnr_adultno = setWc.getString("pnr_adultno");
        String ps_yqrqsj = setWc.getString("ps_yqrqsj");
        String xg_userid = setWc.getString("xg_userid");
        String ct_hyid = setWc.getString("ct_hyid");
        String pnr_cfrqsj = setWc.getString("pnr_cfrqsj");
        String zcfw = setWc.getString("zcfw");
        String version = setWc.getString("version");
        String zf_fkf = setWc.getString("zf_fkf");
        String sjjlfs = setWc.getString("sjjlfs");
        String sfbm = setWc.getString("sfbm");
        String tss_yn = setWc.getString("tss_yn");
        String sfmp = setWc.getString("sfmp");
        String czfrom = setWc.getString("czfrom");
        String pnr_hcglgj = setWc.getString("pnr_hcglgj");
        String zf_je = setWc.getString("zf_je");
        String wctype = setWc.getString("wctype");
        String pt = setWc.getString("pt");
        String ywType = setWc.getString("ywType");
        String yymk = setWc.getString("yymk");
        String ps_fs = setWc.getString("ps_fs");
        String ps_lx = setWc.getString("ps_lx");
        String ps_xxdz = setWc.getString("ps_xxdz");
        String ps_lxr = setWc.getString("ps_lxr");
        String ps_lxdh = setWc.getString("yymk");
        String ps_bz = setWc.getString("ps_bz");
        String sj = setWc.getString("sj");
        String zq_bm = setWc.getString("zq_bm");
        String zq_jc = setWc.getString("zq_jc");
        String ps_yzbm = setWc.getString("ps_yzbm");
        String ps_sf = setWc.getString("ps_sf");
        String ps_cs = setWc.getString("ps_cs");
        String ps_qx = setWc.getString("ps_qx");
        String spy_lxdh = setWc.getString("spy_lxdh");
        String ps_dz = setWc.getString("ps_dz");
        String ps_city = setWc.getString("ps_city");
        String kdgs = setWc.getString("kdgs");

        String bzbz = "采购帐号:" + username + " ；" + docSetWc.getElementsByAttributeValueStarting("name", "bzbz").val();

        // getCplx请求
        String urlGetCplx = "http://47.107.92.22:8150/asms/ticket/order/ticketmanager/asmsticketmanagerzcd/getCplx?notitle=1&cplx=BPET&glgj=1&zkfx=1&hyid="
                + ct_hyid + "&ddbh=" + ddbh;
        System.out.println(urlGetCplx);
        String resGetCplx = commonAsmsGet(urlGetCplx, asmsCookie);
        Document docGetCplx = Jsoup.parse(resGetCplx);
        String cpymc = docGetCplx.select("#cpymc").val();
        String cpyid = docGetCplx.select("#cpyid").val();
        boolean tNoTag = false;
        try {
            // 乘机人信息
            Elements darkredBtnElement = docSetWc.select(".darkredBtn");
            String pnr_no = darkredBtnElement.eq(0).attr("onclick").split("'")[3];
            // 下面split例子：hcidArray[0] = newArray("200917151906936357000005003058");
            String hcidArray = resSetWc.split("hcidArray\\[0\\]")[1].split("\"")[1];

            String urlCjrxx = "http://47.107.92.22:8150/asms/ticket/order/ticketmanager/asmsticketmanagerzcd/getCjrxx?notitle=1&ddbh="
                    + ddbh + "&pnr_no=" + pnr_no + "&lx=3&type=RT&hcidArray=" + hcidArray;
            System.out.println(urlCjrxx);
            String cjrxx = commonAsmsGet(urlCjrxx, asmsCookie);
            System.out.println(cjrxx);
            Document docCjrxx = Jsoup.parse(cjrxx);
            Elements elementTbody = docCjrxx.select("tbody");

            String cjrid = "";
            double je = 0.0; // 账单价+机建+税费
            double cg_cgj = 0.0; // 账单价
            double cg_jsf = 0.0; // 机建
            double cg_tax = 0.0; // 税费
            List<Object> ticket_allArr = new ArrayList<Object>();
            List<String> cjrid_arr = new ArrayList<String>();
            List<String> cpbz_arr = new ArrayList<String>();

            for (int i = 0; i < elementTbody.size(); i++) {
                JSONObject ticket_all = new JSONObject();
                String id = elementTbody.eq(i).attr("id");
                // 有效tbody時提取数据
                if (!"".equals(id)) {
                    cjrid_arr.add("\"" + id.replace("tb_", "") + "\"");
                    cjrid = id.replace("tb_", "");
                    Elements elementInput = elementTbody.eq(i).select("input");
                    for (int j = 0; j < elementInput.size(); j++) {
                        String name = elementInput.eq(j).attr("name");
                        // 有效数据
                        if (!"".equals(name)) {
                            String val = elementInput.eq(j).val();
                            if (name.contains("cpbz[]")) { // 需要另作处理
                                cpbz_arr.add("\"" + val + "\"");
                            }
                            name = name.replace("ticket_all", "").replace("[]", "").replace(".", "");
                            ticket_all.put(name, val);
                            // 账单价
                            if ("cg_cgj".equals(name)) {
                                cg_cgj = cg_cgj + Double.parseDouble(val);
                            }
                            // 机建
                            if ("cg_jsf".equals(name)) {
                                cg_jsf = cg_jsf + Double.parseDouble(val);
                            }
                            // 税费
                            if ("cg_tax".equals(name)) {
                                cg_tax = cg_tax + Double.parseDouble(val);
                            }
                        }
                    }
                    ticket_all.remove("cjrid");
                    ticket_all.remove("cjrid_arr");
                    ticket_all.remove("sfmp");
                    ticket_all.remove("sfzsp");
                    ticket_allArr.add(ticket_all);
                }
            }
            je = cg_cgj + cg_jsf + cg_tax;
            // 乘机人信息中添加票号
            for (int j = 0; j < ticket_allArr.size(); j++) {
                String zjhm = ((JSONObject) ticket_allArr.get(j)).getString("zjhm");
                ((JSONObject) ticket_allArr.get(j)).put("tkno", ticketNo.getString(zjhm)); // 添加票号
//                ((JSONObject) ticket_allArr.get(j)).put("tkno", ""); // 添加票号
                if ("".equals(((JSONObject) ticket_allArr.get(j)).get("tkno"))) {
                    tNoTag = true;
                    throw new NullPointerException("票号为空，回单失败");
                }
            }

            String cpbz_arrStr = cpbz_arr.toString();
            String cjrid_arrStr = cjrid_arr.toString();
            String ticket_allArrStr = ticket_allArr.toString();
            logger.info("ticket_allArrStr==================================" + ticket_allArrStr);

            String scpbz = docCjrxx.getElementsByAttributeValueStarting("name", "scpbz").val();

            // 获取回单保存需要的数据---end

            // 回单保存---start
            // 代理费 = (账单价+机建+税费)-采购金额
            // 代理费率 = 代理费/账单价
            java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
            double dlf1 = je - cgje;
            String dlf1222 = String.valueOf(Double.parseDouble(df.format(dlf1))).split("\\.")[0];
            double dlf = Integer.parseInt(dlf1222);
//            int b = Integer.parseInt(a.toString().split("\\.")[0]);

//            double dlf = Double.parseDouble(String.valueOf(getInt(je - cgje)));
            double jsfl = (dlf / cg_cgj) * 100;
            // 代理费率保留兩位小数
            BigDecimal b = new BigDecimal(jsfl);
            double jsfl2 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            String urlSaveWC = "http://47.107.92.22:8150/asms/ticket/order/ticketmanager/asmsticketmanagerzcd/saveWC";
            System.out.println(urlSaveWC);
            int sjcgje = cgje;
//            String postingStringSaveWC = "{\"p\":\"" + p + "\",\"close\":\"true\",\"submitForm\":\"" + submitForm
//                    + "\",\"fysje\":\"" + fysje + "\",\"ddbh\":\"" + ddbhStr + "\",\"ddzt\":\"" + ddzt
//                    + "\",\"pnr_hkgstldatetime\":\"" + pnr_hkgstldatetime + "\",\"zkfx\":\"" + zkfx + "\",\"ps_pszt\":\""
//                    + ps_pszt + "\",\"longrangegaveiick\":\"\",\"pnr_adultno\":\"" + pnr_adultno + "\",\"ps_yqrqsj\":\""
//                    + ps_yqrqsj + "\",\"xg_userid\":\"" + xg_userid + "\",\"ct_hyid\":\"" + ct_hyid + "\",\"pnr_cfrqsj\":\""
//                    + pnr_cfrqsj + "\",\"zcfw\":\"" + zcfw + "\",\"version\":\"" + version + "\",\"zf_fkf\":\"" + zf_fkf
//                    + "\",\"sjjlfs\":\"" + sjjlfs + "\",\"sfbm\":\"" + sfbm + "\",\"tss_yn\":\"" + tss_yn + "\",\"sfmp\":\""
//                    + sfmp + "\",\"sfzsp\":\"\",\"czfrom\":\"" + czfrom + "\",\"pnr_hcglgj\":\"" + pnr_hcglgj
//                    + "\",\"tbddpj\":\"\",\"zf_je\":\"" + zf_je + "\",\"wctype\":\"" + wctype
//                    + "\",\"yjwctype\":\"1\",\"pt\":\"" + pt + "\",\"ywType\":\"" + ywType + "\",\"yymk\":\"" + yymk
//                    + "\",\"ps_fs\":\"11\",\"ps_lx\":\"1\",\"ps_xxdz\":\"" + ps_xxdz + "\",\"ps_lxr\":\"" + ps_lxr
//                    + "\",\"ps_lxdh\":\"" + ps_lxdh + "\",\"ps_bz\":\"" + ps_bz + "\",\"sj\":\"" + sj + "\",\"zq_bm\":\""
//                    + zq_bm + "\",\"zq_jc\":\"" + zq_jc + "\",\"ps_yzbm\":\"" + ps_yzbm + "\",\"ps_sf\":\"" + ps_sf
//                    + "\",\"ps_cs\":\"" + ps_cs + "\",\"ps_qx\":\"" + ps_qx + "\",\"spy_lxdh\":\"" + spy_lxdh
//                    + "\",\"ps_dz\":\"" + ps_dz + "\",\"ps_city\":\"" + ps_city + "\",\"kdgs\":\"" + kdgs
//                    + "\",\"cjrid\":\"" + cjrid + "\",\"cjrid_arr\":" + cjrid_arrStr + ",\"cpbz\":" + cpbz_arrStr
//                    + ",\"ticket_all\":" + ticket_allArrStr + ",\"scpbz\":\"" + scpbz
//                    + "\",\"cplx\":\"B2C\",\"cplx_list\":\"B2C\",\"newpnr\":\"\",\"newhkgs_pnr\":\"\",\"wcpdw\":\"HBGJ\",\"wcpdwmc\":\"航班管家\","
//                    + "\"zffs\":\"1006309\",\"zfkm\":\"10064151\",\"zf_zfkmmc\":\"乘风易宝\",\"zflsh\":\"" + payNo + "\",\"cpymc\":\""
//                    + cpymc + "\",\"cpyid\":\"" + cpyid + "\",\"jsfl\":\"" + jsfl2 + "\",\"cgje\":\"" + cgje
//                    + "\",\"hk_sfhk\":\"0\",\"dsfy\":\"0.0\",\"pj_hk\":\"0.0\",\"bz\":\"\",\"ps_spymc\":\"\",\"ps_spy\":\"\",\"spy_tel\":\"\",\"ps_spf\":\"\",\"bzbz\":\""
//                    + bzbz.replaceAll("\"", "\\\\\"") + "\"}";
            String postingStringSaveWC = "{\"p\":\"" + p + "\",\"close\":\"true\",\"submitForm\":\"" + submitForm
                    + "\",\"fysje\":\"" + fysje + "\",\"ddbh\":\"" + ddbhStr + "\",\"ddzt\":\"" + ddzt
                    + "\",\"pnr_hkgstldatetime\":\"" + pnr_hkgstldatetime + "\",\"zkfx\":\"" + zkfx + "\",\"ps_pszt\":\""
                    + ps_pszt + "\",\"longrangegaveiick\":\"\",\"pnr_adultno\":\"" + pnr_adultno + "\",\"ps_yqrqsj\":\""
                    + ps_yqrqsj + "\",\"xg_userid\":\"" + xg_userid + "\",\"ct_hyid\":\"" + ct_hyid + "\",\"pnr_cfrqsj\":\""
                    + pnr_cfrqsj + "\",\"zcfw\":\"" + zcfw + "\",\"version\":\"" + version + "\",\"zf_fkf\":\"" + zf_fkf
                    + "\",\"sjjlfs\":\"" + sjjlfs + "\",\"sfbm\":\"" + sfbm + "\",\"tss_yn\":\"" + tss_yn + "\",\"sfmp\":\""
                    + sfmp + "\",\"sfzsp\":\"\",\"czfrom\":\"" + czfrom + "\",\"pnr_hcglgj\":\"" + pnr_hcglgj
                    + "\",\"tbddpj\":\"\",\"zf_je\":\"" + zf_je + "\",\"wctype\":\"" + wctype
                    + "\",\"yjwctype\":\"1\",\"pt\":\"" + pt + "\",\"ywType\":\"" + ywType + "\",\"yymk\":\"" + yymk
                    + "\",\"ps_fs\":\"11\",\"ps_lx\":\"1\",\"ps_xxdz\":\"" + ps_xxdz + "\",\"ps_lxr\":\"" + ps_lxr
                    + "\",\"ps_lxdh\":\"" + ps_lxdh + "\",\"ps_bz\":\"" + ps_bz + "\",\"sj\":\"" + sj + "\",\"zq_bm\":\""
                    + zq_bm + "\",\"zq_jc\":\"" + zq_jc + "\",\"ps_yzbm\":\"" + ps_yzbm + "\",\"ps_sf\":\"" + ps_sf
                    + "\",\"ps_cs\":\"" + ps_cs + "\",\"ps_qx\":\"" + ps_qx + "\",\"spy_lxdh\":\"" + spy_lxdh
                    + "\",\"ps_dz\":\"" + ps_dz + "\",\"ps_city\":\"" + ps_city + "\",\"kdgs\":\"" + kdgs
                    + "\",\"cjrid\":\"" + cjrid + "\",\"cjrid_arr\":" + cjrid_arrStr + ",\"cpbz\":" + cpbz_arrStr
                    + ",\"ticket_all\":" + ticket_allArrStr + ",\"scpbz\":\"" + scpbz
                    + "\",\"cplx\":\"B2C\",\"cplx_list\":\"B2C\",\"newpnr\":\"\",\"newhkgs_pnr\":\"\",\"zffs\":\"1006309\",\"zfkm\":\"10064151\",\"zf_zfkmmc\":\"乘风易宝\",\"zflsh\":\"" + "" + "\",\"hsddh\":\""
                    + orderID + "\",\"cpymc\":\"" + cpymc + "\",\"cpyid\":\"" + cpyid + "\",\"jsfl\":\"" + jsfl2
                    + "\",\"cgje\":\"" + sjcgje
                    + "\",\"hk_sfhk\":\"0\",\"dsfy\":\"0.0\",\"pj_hk\":\"0.0\",\"bz\":\"\",\"ps_spymc\":\"\",\"ps_spy\":\"\",\"spy_tel\":\"\",\"ps_spf\":\"\",\"bzbz\":\""
                    + bzbz.replaceAll("\"", "\\\\\"") + "\"}";
            System.out.println(postingStringSaveWC);
            logger.info("postingStringSaveWC=====================================" + postingStringSaveWC);
            String res2 = commonAsmsPost(urlSaveWC, postingStringSaveWC, asmsCookie);
            logger.info("res2=============================================" + res2);
            System.out.println(res2);
            res = (JSONObject) JSONObject.parse(res2);
            logger.info("res=================================" + JSONObject.toJSONString(res));
        } catch (Exception e) {
            logger.info("catch语句======================================================================");
            //e.printStackTrace();
        } finally {
            OrderInfoServiceImpl orderInfoServiceImpl = (OrderInfoServiceImpl) ApplicationContextUtil.getBean("orderInfoServiceImpl");
            OrderTicketInfo orderTicketInfo = orderInfoServiceImpl.selectIdByOrderId(orderID);
//            OrderTicketInfo orderTicketInfo = orderInfoService.selectIdByOrderId(orderID);
            OrderTicketActiviti orderTicketActiviti = new OrderTicketActiviti();
            if (res == null && tNoTag != true) {
                orderTicketActiviti.setORDER_ID(orderTicketInfo.getID());
                orderTicketActiviti.setINTIME(new Date());
                orderTicketActiviti.setLOG("{'code':'1','msg':'回单成功'}");
                orderTicketActiviti.setINFO("{'code':'1','msg':'回单成功'}");
                orderTicketActiviti.setSTATUS("31");
                OrderActivitiServiceImpl orderActivitiService = (OrderActivitiServiceImpl) ApplicationContextUtil.getBean("orderActivitiServiceImpl");
                orderActivitiService.insertActiciti(orderTicketActiviti);
//                orderActivitiService.insertActiciti(orderTicketActiviti);
            } else if (tNoTag == true) {
                orderTicketActiviti.setORDER_ID(orderTicketInfo.getID());
                orderTicketActiviti.setINTIME(new Date());
                orderTicketActiviti.setLOG("{'code':'0','msg':'回单失败'}");
                orderTicketActiviti.setINFO("{'code':'0','msg':'回单失败'}");
                orderTicketActiviti.setSTATUS("30");
                OrderActivitiServiceImpl orderActivitiService = (OrderActivitiServiceImpl) ApplicationContextUtil.getBean("orderActivitiServiceImpl");
                orderActivitiService.insertActiciti(orderTicketActiviti);
//                orderActivitiService.insertActiciti(orderTicketActiviti);
            } else if (res.getString("status").equals("1") && res.getString("code").equals("0")) {
                orderTicketActiviti.setORDER_ID(orderTicketInfo.getID());
                orderTicketActiviti.setINTIME(new Date());
                orderTicketActiviti.setLOG("{'code':'1','msg':'回单成功'}");
                orderTicketActiviti.setINFO("{'code':'1','msg':'回单成功'}");
                orderTicketActiviti.setSTATUS("31");
                OrderActivitiServiceImpl orderActivitiService = (OrderActivitiServiceImpl) ApplicationContextUtil.getBean("orderActivitiServiceImpl");
                orderActivitiService.insertActiciti(orderTicketActiviti);
//                orderActivitiService.insertActiciti(orderTicketActiviti);
            } else {
                orderTicketActiviti.setORDER_ID(orderTicketInfo.getID());
                orderTicketActiviti.setINTIME(new Date());
                orderTicketActiviti.setLOG("{'code':'0','msg':'回单失败'}");
                orderTicketActiviti.setINFO("{'code':'0','msg':'回单失败'}");
                orderTicketActiviti.setSTATUS("30");
                OrderActivitiServiceImpl orderActivitiService = (OrderActivitiServiceImpl) ApplicationContextUtil.getBean("orderActivitiServiceImpl");
                orderActivitiService.insertActiciti(orderTicketActiviti);
//                orderActivitiService.insertActiciti(orderTicketActiviti);
            }
        }
        return res;
    }
}
